import * as cloudDb from '@agconnect/database-server';
import { topic } from './model/topic';
import { user_topic } from './model/user_topic';
import { TopicResponse } from './model/TopicResponse';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;

  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      let cloudDbInstance;
      try {
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async queryTopics(userid, type) {
    let listData = [];
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }

    // 查询用户关注的主题
    let userTopicsIds = []
    if (userid) {
      const userTopicQuery = cloudDb.CloudDBZoneQuery.where(user_topic).equalTo("user_id", userid);
      const userTopicResp = await this.cloudDbZone.executeQuery(userTopicQuery);
      let userTopics = userTopicResp.getSnapshotObjects();
      this.logger.info("query userTopic success ");
      console.log('userTopicResp=>', userTopicResp.getSnapshotObjects());
      if (userTopics.length > 0) {
        for (let i = 0; i < userTopics.length; i++) {
          userTopicsIds.push(userTopics[i].getTopic_id())
        }
      }
    }

    // 查询所有主题
    const cloudDBZoneQuery = cloudDb.CloudDBZoneQuery.where(topic);
    cloudDBZoneQuery.equalTo("type", type);
    cloudDBZoneQuery.in("id", userTopicsIds);
    const resp = await this.cloudDbZone.executeQuery(cloudDBZoneQuery);
    listData = resp.getSnapshotObjects();
    this.logger.info("query topic success ");
    console.log('resp=>', resp.getSnapshotObjects());

    let responseList = []
    if (listData.length > 0) {
      for (let i = 0; i < listData.length; i++) {
        let topic: topic = listData[i];
        responseList.push(new TopicResponse(
          topic.getId(),
          topic.getName(),
          topic.getType(),
          topic.getIcon(),
          true
        ));
      }

      return responseList
    } else {
      return undefined;
    }
  }
}